package org.bbs.demo.reply.api;


import org.bbs.demo.advice.BusinessException;
import org.bbs.demo.common.BBSConstants;
import org.bbs.demo.common.Result;
import org.bbs.demo.reply.dao.ReplyDao;
import org.bbs.demo.reply.dto.ReplyDto;
import org.bbs.demo.utils.jwtutil.JWTutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
@RequestMapping("/comment")
@Transactional //事务声明，表示该类的所有方法都是事务性的，即方法中的所有访问数据库操作构成了一个整体事务，具有原子性
public class ReplyApi {
    @Autowired
    private ReplyDao replydao;

    @PostMapping("/reply/add")
    public Result info(@RequestBody ReplyDto replydto, @RequestHeader String Token){
        try{
            String userid = JWTutil.getUserID(Token);
            String rid = UUID.randomUUID().toString().replace("-","");
            replydto.setUser_id(userid);
            replydto.setR_id(rid);
            if(replydao.findUser(userid) == null){
                throw new BusinessException("用户id不存在");
                //return Result.err(BBSConstants.CODE_ERR_BUSINESS,"用户id不存在");
            }
            if(replydao.findTopic(replydto.getTopic_id()) == null){
                throw new BusinessException("文章id不存在");
                //return Result.err(BBSConstants.CODE_ERR_BUSINESS,"文章id不存在");
            }
            replydao.addReply(replydto);
            replydao.updateReplyNum(replydto.getTopic_id());
            return Result.OK("评论成功",replydto);
        } catch (DuplicateKeyException err) {
            throw new BusinessException("评论失败");
            //return Result.err(BBSConstants.CODE_ERR_SYS, "评论失败");
        }
    }
}
